#!/bin/bash -x
set -x
ProgName=$(basename $0)
BaseDir=$(dirname $(readlink -f "$0"))
SYSOM_STOP_LOG=$LOG_HOME/sysom_stop.log

####################################################################################################################
# Helper functions
####################################################################################################################

red() {
    printf '\33[1;31m%b\n\33[0m' "$1"
}

green() {
    printf '\33[1;32m%b\n\33[0m' "$1"
}

do_stop_microservices() {
    target=$1
    targets=(${target//,/ })
    for target in ${targets[*]}; do
        for service in $(ls ${MICROSERVICE_HOME} | grep ${target}); do
            service_deploy_script_dir=${MICROSERVICE_SCRIPT_HOME}/${service}

            ################################################################################################
            # Perform service initial script
            ################################################################################################

            pushd ${service_deploy_script_dir}

            green "$service_deploy_script_dir Stopping..................................."
            if [ ! -f "${service_deploy_script_dir}/stop.sh" ]; then
                popd
                continue
            fi
            bash -x ${service_deploy_script_dir}/stop.sh
            if [ $? -ne 0 ]; then
                red "$service_deploy_script_dir stop fail, please check..................................."
                red "sysom stop failed, exit 1"
                exit 1
            fi
            popd
        done
    done
}

do_stop_environment() {
    target=$1
    targets=(${target//,/ })
    for target in ${targets[*]}; do
        for env in $(ls ${ENVIRONMENT_HOME} | grep ${target}); do
            target_dir=${ENVIRONMENT_HOME}/${env}
            if [ ! -d "${target_dir}" ] || [ ! -f "${target_dir}/stop.sh" ]; then
                continue
            fi

            pushd ${target_dir}

            green "$target_dir Stopping..................................."
            bash -x ${target_dir}/stop.sh
            if [ $? -ne 0 ]; then
                red "$target_dir stop fail, please check..................................."
                red "sysom stop failed, exit 1"
                exit 1
            fi

            popd
        done
    done
}

do_stop_deps() {
    target=$1
    targets=(${target//,/ })
    for target in ${targets[*]}; do
        for dep in $(ls ${DEPS_HOME} | grep ${target}); do
            target_dir=${DEPS_HOME}/${dep}
            if [ ! -d "${target_dir}" ] || [ ! -f "${target_dir}/stop.sh" ]; then
                continue
            fi

            pushd ${target_dir}

            green "$target_dir Stopping..................................."
            bash -x ${target_dir}/stop.sh
            if [ $? -ne 0 ]; then
                red "$target_dir stop fail, please check..................................."
                red "sysom stop failed, exit 1"
                exit 1
            fi
            popd
        done

    done
}

ensure_supervisor_active() {
    # 1. First ensure supervisor installed
    rpm -q --quiet supervisor || yum install -y supervisor

    # 2. Then ensure supervisord is active
    result=$(systemctl is-active supervisord)
    if [ "$result" != "active" ]; then
        systemctl enable supervisord
        systemctl start supervisord
    fi
}

####################################################################################################################
# Subcommands
####################################################################################################################

sub_help() {
    echo "Usage: $ProgName <subcommand> [options]"
    echo "Subcommands:"
    echo "    all   Stop all modules"
    echo "    env   [ALL | <base_env_name>]        Stop all enviroment or specific enviroment"
    echo "          Example: $ProgName env env"
    echo "          Example: $ProgName env sdk"
    echo "    deps  [ALL | <deps_name>]            Stop all deps or specific dep"
    echo "          Example: $ProgName dep mysql"
    echo "          Example: $ProgName dep grafana"
    echo "    ms    [ALL | <service_name>]         Stop all microservices or specific microservice"
    echo "          Example: $ProgName ms sysom_diagnosis"
    echo ""
    echo "For help with each subcommand run:"
    echo "$ProgName <subcommand> -h|--help"
    echo ""
}

sub_ALL() {
    sub_web
    sub_ms ALL
    sub_env ALL
    sub_deps ALL
}

sub_all() {
    sub_ALL
}

sub_env() {
    sub_environment $@
}

# -> env + sdk
sub_environment() {
    target=$1
    if [ "$target" == "ALL" ]; then
        # Stop all enviroment
        for env in $(ls -r $ENVIRONMENT_HOME); do
            if [ ! -d "${ENVIRONMENT_HOME}/${env}" ]; then
                continue
            fi
            do_stop_environment $env
        done
    else
        # Stop specific enviroment
        do_stop_environment $target
    fi
}

sub_ms() {
    sub_microservice $@
}

sub_server() {
    sub_microservice $@
}

# All microservices
sub_microservice() {
    target=$1
    if [ "$target" == "ALL" ]; then
        # stop all microservices
        for microservice in $(ls -r $MICROSERVICE_HOME); do
            if [ ! -d "${MICROSERVICE_HOME}/${microservice}" ]; then
                continue
            fi
            do_stop_microservices ${microservice}
        done
    else
        # stop specific microservices
        do_stop_microservices $target
    fi
}

sub_deps() {
    target=$1
    if [ "$target" == "ALL" ]; then
        # stop all deps
        for dep in $(ls -r $DEPS_HOME); do
            if [ ! -d "${DEPS_HOME}/${dep}" ]; then
                continue
            fi
            do_stop_deps ${dep}
        done
    else
        # stop specific deps
        do_stop_deps $target
    fi
}

sub_web() {
    # do nothing
    echo ""
}

subcommand=$1
case $subcommand in
"" | "-h" | "--help")
    sub_help
    ;;
*)
    ensure_supervisor_active | tee ${SYSOM_STOP_LOG}
    shift
    sub_${subcommand} $@ | tee ${SYSOM_STOP_LOG}
    if [ $? = 127 ]; then
        echo "Error: '$subcommand' is not a known subcommand." >&2
        echo "       Run '$ProgName --help' for a list of known subcommands." >&2
        exit 1
    fi
    ;;
esac
